import {
  queryLogisticsRule,
  queryLogisticsByCode,
  trailUpdateList,
  opreateTrack,
  selectFileList,
  selectEvents,
} from '@/services/order/trail';
import prompt from '@/components/Prompt';

export default {
  namespace: 'trailUpdate',

  state: {
    orderResult: {
      code: 0,
      messageId: '',
      messageStr: '',
      result: [],
    },
    data: [],
    trailUpdateList: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryLogisticsRule, payload);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *queryCode({ payload }, { call, put }) {
      const orderResult = yield call(queryLogisticsByCode, payload);
      yield put({
        type: 'save',
        payload: {
          orderResult: orderResult,
        },
      });
    },
    //轨迹更新：
    *trailUpdateList({ payload, callback }, { call, put }) {
      const response = yield call(trailUpdateList, payload);
      const { code, data } = response;
      callback && callback(response);
      if (code !== 0) return;
      const infoList = {
        list: data || [],
      };
      yield put({
        type: 'detail',
        payload: { trailUpdateList: { [payload.orderNo]: infoList } },
      });
    },
    *opreateTrack({ payload, callback }, { call, put }) {
      const response = yield call(opreateTrack, payload);
      const { code, message } = response;
      if (code !== 0) return;
      prompt({
        content: `保存${message}`,
        type: 'success',
      });
      callback && callback();
    },

    *selectEvents({ payload, callback }, { call, put }) {
      const response = yield call(selectEvents, payload);
      const { code, message, data } = response;
      if (code !== 0) return;
      callback && callback(data);
    },
    *setData({ payload }, { call, put }) {
      yield put({
        type: 'save',
        payload: [],
      });
    },
    /**
     * 设置表单参数
     */
    *allValus({ payload }, { _, put }) {
      yield put({
        type: 'saveAllValus',
        payload,
      });
    },
    *selectFileList({ payload, callback }, { call }) {
      const response = yield call(selectFileList, payload);
      const { code, message, data } = response;
      if (code === 0) {
        if (callback) callback(data);
      }
    },
  },

  reducers: {
    //设置表单参数
    saveAllValus(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    detail(state, { payload }) {
      let param = '';
      for (let k in payload) {
        param = k;
      }
      return {
        ...state,
        [param]: { ...state[param], ...payload[param] },
      };
    },
  },
};
